﻿using System;
using System.Data;

namespace MySqlQueryToolkit.DataAccess
{
    public class UnsafeMySqlDataAccess : MySqlDataAccess, IUnsafeDataAccess
    {
        public UnsafeMySqlDataAccess(string connectionString) : base(connectionString)
        {
        }

        public void OpenConnection()
        {
            Connection.Open();
        }

        public void CloseConnection()
        {
            Connection.Close();
        }

        public override int ExecuteNonQuery()
        {
            try
            {
                return _command.ExecuteNonQuery();
            }
            finally
            {
                _command.Parameters.Clear();
            }
        }

        public override void ExecuteReader(Action<IDataReader> dataMapperAction)
        {
            ExecuteReader(dataMapperAction, CommandBehavior.Default);
        }

        public override void ExecuteReader(Action<IDataReader> dataMapperAction, CommandBehavior behavior)
        {
            try
            {
                using (IDataReader reader = _command.ExecuteReader(behavior))
                {
                    dataMapperAction(reader);
                }
            }
            finally
            {
                _command.Parameters.Clear();
            }
        }

        private bool _alreadyDisposed;

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool isDisposing)
        {
            if (_alreadyDisposed)
            {
                return;
            }

            Connection.Close();
            _alreadyDisposed = true;
        }
    }
}
